var AV = require('leanengine');
var async = require('async');
var Q = require('q') ;

var Classify = AV.Object.extend('Classify');
var Product = AV.Object.extend('Product');
module.exports = {
    findTuiJianProduct:function(cid_type){
        var promise = new AV.Promise();
        async.waterfall([
            //根据cid——type找出对应的分类
            function(callback){
                var query = new AV.Query(Classify);
                query.equalTo('gjz',cid_type);
                query.first().then(function(data){
                    if(data){
                        callback(null, data.id);
                    }else{
                        callback({code:-1});
                    }
                }).catch(function(err){
                    callback({code:-1});
                })
            },
            function(cid,callback){
                var query = new AV.Query(Product);
                query.equalTo('cid',parseInt(cid));
                query.equalTo('status',1);
                query.skip(0);
                //query.limit(2);
                query.find().then(function(data){
                    callback(null, data)
                }).catch(function(err){
                    callback({code:-1});
                });
            },
            function(pros,callback){
                //格式化商品列表
                var array = [] ;
                async.each(pros,function(pro,cb){
                    //console.log(JSON.parse(pro.get('picurlarray'))[0])
                    //console.log(pro.get('spec'));
                    var psid = 0 ;
                    var index = 0 ;
                    for(var k in pro.get('spec')){
                        index ++ ;
                        if(index === 1 ){
                            psid = k ;
                        }
                    }

                    array.push({id:pro.id,name:pro.get('name'),price:pro.get('minPrice'),psid:psid,spname:pro.get('minSpecName'),pic:JSON.parse(pro.get('picurlarray'))[0]});
                    cb(null);
                },function(){
                    callback(null, array);
                })
            }
        ],function(err,results) {
            if (err) {
                promise.reject(err);
            }else{
                promise.resolve(results);
            }
        });
        return promise;
    },
}